package com.company.project.controller.ldjsc.calendar;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cn.dev33.satoken.annotation.SaCheckPermission;

import com.company.project.entity.ldjsc.calendar.ZyCalendarEntity;
import com.company.project.service.ldjsc.calendar.ZyCalendarService;
import com.company.project.vo.ldjsc.calendar.ZyCalendarVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

import com.company.project.common.utils.DataResult;


/**
 * 日历
 *
 * @author wenbin
 * @email *****@mail.com
 * @date 2025-07-22 09:44:54
 */
@Controller
@RequestMapping("/sxzy")
public class ZyCalendarController {
    @Autowired
    private ZyCalendarService zyCalendarService;

    @Value("${rl.api-roll.app-id}")
    private String appIdRoll;
    @Value("${rl.api-roll.app-secret}")
    private String appSsecretRoll;
    @Value("${rl.api-roll.url}")
    private String urlRoll;

    /**
     * 日历
     *
     * @return
     */
    @GetMapping("/calendar/year")
    @ResponseBody
    public DataResult citySeven(String year, String month, String day) throws IOException {

        if (StringUtils.isNotBlank(year) &&
                StringUtils.isNotBlank(month) &&
                StringUtils.isNotBlank(day)){
            return DataResult.fail("参数错误");
        }

        //查询当前年月的日历
        List<ZyCalendarEntity> list;
        LambdaQueryWrapper<ZyCalendarEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(StringUtils.isNotBlank(year), ZyCalendarEntity::getYear, year);
        queryWrapper.eq(StringUtils.isNotBlank(month), ZyCalendarEntity::getMonth, month);
        queryWrapper.eq(StringUtils.isNotBlank(day), ZyCalendarEntity::getData, day);
        queryWrapper.orderByAsc(ZyCalendarEntity::getData);
        list = zyCalendarService.list(queryWrapper);
        //如果是空 则调用接口获取（当前一整年的）
        if (list == null || list.size() == 0) {
            if (StringUtils.isBlank(year)) {
                year = day.substring(0, 4);
            }
            List<Map<String, Object>> holidayData = this.getHolidayData(year, false, appIdRoll, appSsecretRoll);
            this.saveHolidayData(holidayData);
            //重新调用
            list = zyCalendarService.list(queryWrapper);
        }
        if (StringUtils.isNotBlank(month)) {
            aroundTheMoon(list);
            List<Long> ids = new ArrayList<>();
            for (ZyCalendarEntity zyCalendarEntity : list) {
                ids.add(zyCalendarEntity.getId());
            }
            LambdaQueryWrapper<ZyCalendarEntity> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.in(ZyCalendarEntity::getId, ids);
            queryWrapper1.orderByAsc(ZyCalendarEntity::getData);
            list = zyCalendarService.list(queryWrapper1);
        }

        List<ZyCalendarVo> zyCalendarVoList = new ArrayList<>();
        for (ZyCalendarEntity zyCalendarEntity : list) {

            String weekDay = zyCalendarEntity.getWeekDay();
            if (weekDay.equals("7")) {
                zyCalendarEntity.setWeekDay("日");
            } else if (weekDay.equals("6")) {
                zyCalendarEntity.setWeekDay("六");
            } else if (weekDay.equals("1")) {
                zyCalendarEntity.setWeekDay("一");
            } else if (weekDay.equals("2")) {
                zyCalendarEntity.setWeekDay("二");
            } else if (weekDay.equals("3")) {
                zyCalendarEntity.setWeekDay("三");
            } else if (weekDay.equals("4")) {
                zyCalendarEntity.setWeekDay("四");
            } else if (weekDay.equals("5")) {
                zyCalendarEntity.setWeekDay("五");
            }

            ZyCalendarVo zyCalendarVo = new ZyCalendarVo();
            BeanUtils.copyProperties(zyCalendarEntity, zyCalendarVo);
            zyCalendarVo.setWeekdayIsWork("0");
            if (StringUtils.isNotBlank(zyCalendarEntity.getType())){
                if (weekDay.equals("6") || weekDay.equals("7")) {
                    if (zyCalendarEntity.getType().equals("0")) {
                        zyCalendarVo.setWeekdayIsWork("1");
                    }
                }
            }

            zyCalendarVoList.add(zyCalendarVo);
        }

        return DataResult.success(zyCalendarVoList);
    }

    /**
     * 根据当前月的第一条和最后一天获取日期
     *
     * @param list
     */
    private void aroundTheMoon(List<ZyCalendarEntity> list) {

        //当前月份第一天星期几
        ZyCalendarEntity zyCalendarEntity = list.get(0);
        //当前月份最后一天星期几
        ZyCalendarEntity zyCalendarEntity1 = list.get(list.size() - 1);
        String weekDay = zyCalendarEntity.getWeekDay();
        String weekDay1 = zyCalendarEntity1.getWeekDay();
        //当前月份
        String data = zyCalendarEntity.getData();
        String data1 = zyCalendarEntity1.getData();


        //前几天
        if (!weekDay.equals("7")) {
            LambdaQueryWrapper<ZyCalendarEntity> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.lt(ZyCalendarEntity::getData, data);
            queryWrapper.orderByDesc(ZyCalendarEntity::getData);
            queryWrapper.last("limit " + weekDay);
            List<ZyCalendarEntity> list1 = zyCalendarService.list(queryWrapper);
            list.addAll(list1);
        }

        //后几天
        if (!weekDay1.equals("6")) {
            String day = "";

            if (weekDay1.equals("7")) {
                day = "6";
            } else if (weekDay1.equals("1")) {
                day = "5";
            } else if (weekDay1.equals("2")) {
                day = "4";
            } else if (weekDay1.equals("3")) {
                day = "3";
            } else if (weekDay1.equals("4")) {
                day = "2";
            } else if (weekDay1.equals("5")) {
                day = "1";
            }
            LambdaQueryWrapper<ZyCalendarEntity> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.gt(ZyCalendarEntity::getData, data1);
            queryWrapper.orderByAsc(ZyCalendarEntity::getData);
            queryWrapper.last("limit " + day);
            List<ZyCalendarEntity> list1 = zyCalendarService.list(queryWrapper);
            list.addAll(list1);
        }
    }


    private void saveHolidayData(List<Map<String, Object>> holidayData) {
        List<ZyCalendarEntity> zyCalendarEntities = new ArrayList<>();
        for (Map<String, Object> holiday : holidayData) {
            Object days = holiday.get("days");
            if (days instanceof List) {
                List<?> daysList = (List<?>) days;

                for (Object day : daysList) {
                    if (day instanceof Map) {
                        Map<String, Object> dayMap = (Map<String, Object>) day;
                        ZyCalendarEntity entity = new ZyCalendarEntity();
                        entity.setYear(holiday.get("year").toString());
                        entity.setMonth(holiday.get("month").toString());
                        entity.setData(dayMap.get("date").toString());
                        entity.setWeekDay(dayMap.get("weekDay").toString());
                        entity.setYearTips(dayMap.get("yearTips").toString());
                        entity.setType(dayMap.get("type").toString());
                        entity.setTypeDes(dayMap.get("typeDes").toString());
                        entity.setChineseZodiac(dayMap.get("chineseZodiac").toString());
                        entity.setSolarTerms(dayMap.get("solarTerms").toString());
                        entity.setLunarCalendar(dayMap.get("lunarCalendar").toString());
                        entity.setSuit(dayMap.get("suit").toString());
                        entity.setDayOfYear(dayMap.get("dayOfYear").toString());
                        entity.setWeekOfYear(dayMap.get("weekOfYear").toString());
                        entity.setConstellation(dayMap.get("constellation").toString());
                        entity.setIndexWorkDayOfMonth(dayMap.get("indexWorkDayOfMonth").toString());
                        entity.setDetailsType(dayMap.get("detailsType").toString());

                        if (dayMap.get("typeDes").toString().equals("春节")
                                && !dayMap.get("lunarCalendar").toString().equals("正月初一")) {
                            entity.setDetailsType("2");
                        }

                        if (dayMap.get("typeDes").toString().equals("劳动节")
                                && !dayMap.get("date").toString().equals("2025-05-01")) {
                            entity.setDetailsType("2");
                        }

                        if (dayMap.get("typeDes").toString().equals("国庆节")
                                && !dayMap.get("date").toString().equals("2025-10-01")) {
                            entity.setDetailsType("2");
                        }


                        zyCalendarEntities.add(entity);
                    }
                }
            }
        }
        zyCalendarService.saveBatch(zyCalendarEntities);
    }

    private List<Map<String, Object>> getHolidayData(String year, boolean ignoreHoliday, String appId, String appSecret) throws IOException {
        String requestUrl = urlRoll + year + "?ignoreHoliday=" + ignoreHoliday + "&app_id=" + appId + "&app_secret=" + appSecret;

        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // 解析 JSON 响应
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> result = objectMapper.readValue(response.toString(), Map.class);
        return (List<Map<String, Object>>) result.get("data");
    }


    //https://api.songzixian.com/api/perpetual-calendar?dataSource=local_perpetual_calendar&date=2023-11-08

    /**
     * 获取未来50年的日历
     */
    @GetMapping("/index/fifty")
    public DataResult indexFifty(String data1) throws IOException {

        LambdaQueryWrapper<ZyCalendarEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.gt(ZyCalendarEntity::getData, data1);
        List<ZyCalendarEntity> list = zyCalendarService.list(queryWrapper);

//        List<ZyCalendarEntity> zyCalendarEntities = new ArrayList<>();

        for (ZyCalendarEntity zyCalendarEntity : list) {
            String jsonData = getPerpetualCalendar(zyCalendarEntity.getData());

            // 使用ObjectMapper解析JSON
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> resultMap = objectMapper.readValue(jsonData, Map.class);

            // 提取所需字段
            Map<String, Object> data = (Map<String, Object>) resultMap.get("data");
            Map<String, Object> gregorianInfo = (Map<String, Object>) data.get("gregorianInfo");
            Map<String, Object> lunarInfo = (Map<String, Object>) data.get("lunarInfo");

            // 获取 dayOfWeek 和 chineseDate

            //周几
            String dayOfWeek = (String) gregorianInfo.get("dayOfWeek");
            String dayOfWeek1 = "";
            if (dayOfWeek.equals("星期六")){
                dayOfWeek1 = "6";
            } else if (dayOfWeek.equals("星期日")){
                dayOfWeek1 = "7";
            } else if (dayOfWeek.equals("星期一")){
                dayOfWeek1 = "1";
            } else if (dayOfWeek.equals("星期二")){
                dayOfWeek1 = "2";
            } else if (dayOfWeek.equals("星期三")){
                dayOfWeek1 = "3";
            } else if (dayOfWeek.equals("星期四")){
                dayOfWeek1 = "4";
            } else if (dayOfWeek.equals("星期五")){
                dayOfWeek1 = "5";
            }

            zyCalendarEntity.setWeekDay(dayOfWeek1);

            //农历日期
            String chineseDate = (String) lunarInfo.get("chineseDate");
            String substring = chineseDate.substring(5);
            zyCalendarEntity.setLunarCalendar(substring);

            zyCalendarService.updateById(zyCalendarEntity);
//            zyCalendarEntities.add(zyCalendarEntity);
        }
//        zyCalendarService.updateBatchById(zyCalendarEntities);

        return DataResult.success();
    }

//    @GetMapping("/index/fifty")
//    @ResponseBody
//    public DataResult indexFifty() {
//
//        for (int i = 2026; i <2076; i++) {
//            String data = "";
//            if (i % 4 != 0){
//                for (int j = 1; j <13; j++) {
//                    if (j == 1 || j == 3 || j == 5 || j == 7 || j == 8 || j == 10 || j == 12){
//                        for (int k = 1; k <=31; k++) {
//                            String yue1 = j + "";
//                            if (j < 10){
//                                yue1 = "0" + j;
//                            }
//                            String k1 = k + "";
//                            if (k < 10){
//                                k1 = "0" + k;
//                            }
//                            data = i + "-" + yue1 + "-" + k1;
//
//                            ZyCalendarEntity zyCalendarEntity = new ZyCalendarEntity();
//                            zyCalendarEntity.setYear(i + "");
//                            zyCalendarEntity.setMonth(j + "");
//                            zyCalendarEntity.setData(data);
//                            zyCalendarService.save(zyCalendarEntity);
//                        }
//                    } else if (j == 2){
//                        for (int k = 1; k <=28; k++) {
//                            String yue1 = j +  "";
//                            if (j < 10){
//                                yue1 = "0" + j;
//                            }
//                            String k1 = k + "";
//                            if (k < 10){
//                                k1 = "0" + k;
//                            }
//                            data = i + "-" + yue1 + "-" + k1;
//                            ZyCalendarEntity zyCalendarEntity = new ZyCalendarEntity();
//                            zyCalendarEntity.setYear(i + "");
//                            zyCalendarEntity.setMonth(j + "");
//                            zyCalendarEntity.setData(data);
//                            zyCalendarService.save(zyCalendarEntity);
//                        }
//                    } else {
//                        for (int k = 1; k <=30; k++) {
//                            String yue1 = j +  "";
//                            if (j < 10){
//                                yue1 = "0" + j;
//                            }
//                            String k1 = k + "";
//                            if (k < 10){
//                                k1 = "0" + k;
//                            }
//                            data = i + "-" + yue1 + "-" + k1;
//                            ZyCalendarEntity zyCalendarEntity = new ZyCalendarEntity();
//                            zyCalendarEntity.setYear(i + "");
//                            zyCalendarEntity.setMonth(j + "");
//                            zyCalendarEntity.setData(data);
//                            zyCalendarService.save(zyCalendarEntity);
//                        }
//                    }
//                }
//            }else {
//                for (int j = 1; j <13; j++) {
//                    if (j == 1 || j == 3 || j == 5 || j == 7 || j == 8 || j == 10 || j == 12){
//                        for (int k = 1; k <=31; k++) {
//                            String yue1 = j +  "";
//                            if (j < 10){
//                                yue1 = "0" + j;
//                            }
//                            String k1 = k + "";
//                            if (k < 10){
//                                k1 = "0" + k;
//                            }
//                            data = i + "-" + yue1 + "-" + k1;
//                            ZyCalendarEntity zyCalendarEntity = new ZyCalendarEntity();
//                            zyCalendarEntity.setYear(i + "");
//                            zyCalendarEntity.setMonth(j + "");
//                            zyCalendarEntity.setData(data);
//                            zyCalendarService.save(zyCalendarEntity);
//                        }
//                    } else if (j == 2){
//                        for (int k = 1; k <=29; k++) {
//                            String yue1 = j +  "";
//                            if (j < 10){
//                                yue1 = "0" + j;
//                            }
//                            String k1 = k + "";
//                            if (k < 10){
//                                k1 = "0" + k;
//                            }
//                            data = i + "-" + yue1 + "-" + k1;
//                            ZyCalendarEntity zyCalendarEntity = new ZyCalendarEntity();
//                            zyCalendarEntity.setYear(i + "");
//                            zyCalendarEntity.setMonth(j + "");
//                            zyCalendarEntity.setData(data);
//                            zyCalendarService.save(zyCalendarEntity);
//                        }
//                    } else {
//                        for (int k = 1; k <=30; k++) {
//                            String yue1 = j +  "";
//                            if (j < 10){
//                                yue1 = "0" + j;
//                            }
//                            String k1 = k + "";
//                            if (k < 10){
//                                k1 = "0" + k;
//                            }
//                            data = i + "-" + yue1 + "-" + k1;
//                            ZyCalendarEntity zyCalendarEntity = new ZyCalendarEntity();
//                            zyCalendarEntity.setYear(i + "");
//                            zyCalendarEntity.setMonth(j + "");
//                            zyCalendarEntity.setData(data);
//                            zyCalendarService.save(zyCalendarEntity);
//                        }
//                    }
//                }
//            }
//        }
//        return DataResult.success();
//    }


    public static String getPerpetualCalendar(String date)  {
        try {
            String urlString = "https://api.songzixian.com/api/perpetual-calendar?dataSource=local_perpetual_calendar&date=" + date;
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream())
            );

            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            Thread.sleep(500);
            // 返回JSON字符串
            return response.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 跳转到页面
     */
    @GetMapping("/index/zyCalendar")
    public String zyCalendar() {
        return "zycalendar/list";
    }


    @ApiOperation(value = "查询分页数据")
    @PostMapping("zyCalendar/listByPage")
    @SaCheckPermission("zyCalendar:list")
    @ResponseBody
    public DataResult findListByPage(@RequestBody ZyCalendarEntity zyCalendar) {
        LambdaQueryWrapper<ZyCalendarEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        queryWrapper.eq(zyCalendar.getId() != null, ZyCalendarEntity::getId, zyCalendar.getId());
        queryWrapper.orderByDesc(ZyCalendarEntity::getId);
        IPage<ZyCalendarEntity> iPage = zyCalendarService.page(zyCalendar.getQueryPage(), queryWrapper);
        return DataResult.success(iPage);
    }


    @ApiOperation(value = "新增")
    @PostMapping("zyCalendar/add")
    @SaCheckPermission("zyCalendar:add")
    @ResponseBody
    public DataResult add(@RequestBody ZyCalendarEntity zyCalendar) {
        zyCalendarService.save(zyCalendar);
        return DataResult.success();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("zyCalendar/delete")
    @SaCheckPermission("zyCalendar:delete")
    @ResponseBody
    public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
        zyCalendarService.removeByIds(ids);
        return DataResult.success();
    }

    @ApiOperation(value = "更新")
    @PutMapping("zyCalendar/update")
    @SaCheckPermission("zyCalendar:update")
    @ResponseBody
    public DataResult update(@RequestBody ZyCalendarEntity zyCalendar) {
        zyCalendarService.updateById(zyCalendar);
        return DataResult.success();
    }


}
